package com.chenjj.java.juc.tools.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

/**
 * 一个简单的CoundownLatch实现，为了弄清楚CoundownLatch源码里那些复杂的操作比我这个简单实现的优点在哪里。
 *
 * 通过一个AtomicInteger类型的计数器+LockSupport.park/unpark完成。
 */
public class CountDownLatchSimlpe1 extends CountDownLatch {
    private AtomicInteger count;
    private Thread thread;

    public CountDownLatchSimlpe1(int count) {
        super(count);
        this.count = new AtomicInteger(count);
    }

    @Override
    public void await() throws InterruptedException {
        thread = Thread.currentThread();
        LockSupport.park(thread);
    }

    @Override
    public void countDown() {
        int c = count.decrementAndGet();
        if (c==0){
            LockSupport.unpark(thread);
        }
    }
}
